
from django.shortcuts import render

# Create your views here.
import json
from django import http
from django.views import View
from django.http import JsonResponse
from django_redis import get_redis_connection
from apps.goods.models import SKU
from django.contrib.auth.mixins import LoginRequiredMixin

class CartView(LoginRequiredMixin,View):

    def post(self,request):
        # 1. 接收参数
        data = json.loads(request.body.decode())
        # 2. 提取参数
        sku_id = data.get('sku_id')
        count = data.get('count')
        # 3. 验证参数
        # 3.1 判断商品id是否存储
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'没有此商品'})
        # 3.2 count应该是 数值
        try:
            count = int(count)
        except Exception:
            count = 1
        # 4. 数据入库
        # 4.1 链接redis
        redis_cli = get_redis_connection('carts')
        # ①创建管道
        pipeline = redis_cli.pipeline()
        # 4.2 操作hash
        # ②让管道收集指令
        pipeline.hincrby('carts_%s'%request.user.id,sku_id,count)
        # redis_cli.hincrby('carts_%s'%request.user.id,sku_id,count)
        # 4.3 操作set
        pipeline.sadd('selected_%s'%request.user.id,sku_id)
        # redis_cli.sadd('selected_%s'%request.user.id,sku_id)
        # ③执行管道
        pipeline.execute()
        # 5. 返回响应
        return JsonResponse({'code':0,'count':count})


    def get(self,request):
        # 1. 根据需求查询数据 (redis)
        # 1.1 链接redis
        redis_cli = get_redis_connection('carts')
        # ①创建管道
        # pipeline = redis_cli.pipeline()
        # 1.2 获取hash
        # ②管道收集数据
        sku_id_counts = redis_cli.hgetall('carts_%s'%request.user.id)
        # 1.3 获取set
        selected_ids = redis_cli.smembers('selected_%s'%request.user.id)
        # ③执行管道
        # pipeline.execute()
        # 1.4 根据商品的id查询商品的详细信息
        data_list = []
        for sku_id,count in sku_id_counts.items():
            sku = SKU.objects.get(id=sku_id)
            # 2. 将对象转换为字典数据
            data_list.append({
                'id':sku.id,
                'count':int(count),
                'selected': sku_id in selected_ids,
                'amount': int(count) * int(sku.price),
                'name': sku.name,
                'price': int(sku.price),
                'default_image_url': sku.default_image.url
            })
        # 3. 返回响应
        return JsonResponse({
            "code":0,
            "errmsg":"OK",
            "cart_skus": data_list
        })


    def put(self,request):
        # 1. 接收参数
        data = json.loads(request.body.decode())
        # 2. 提取参数
        sku_id = data.get('sku_id')
        count = data.get('count')
        selected = data.get('selected')
        # 3. 验证参数
        # 4. 数据更新
        # 4.1 链接redis
        redis_cli = get_redis_connection('carts')
        # 4.2 更新hash
        redis_cli.hset('carts_%s'%request.user.id,sku_id,count)
        # 4.3 更新set
        if selected:
            redis_cli.sadd('selected_%s'%request.user.id,sku_id)
        else:
            redis_cli.srem('selected_%s'%request.user.id,sku_id)
        # 5. 返回响应
        return JsonResponse({'code':0,'cart_sku':{'count':count,'selected':selected}})


    def delete(self,request):
        # 1. 接收数据
        data = json.loads(request.body.decode())
        # 2. 提取数据
        sku_id = data.get('sku_id')
        # 3. 根据id查询数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'数据不存在'})
        # 4. 删除数据
        # 4.1 链接redis
        redis_cli = get_redis_connection('carts')
        pipeline = redis_cli.pipeline()
        # 4.2 删除hash
        # redis_cli.hdel('carts_%s'%request.user.id,sku_id)
        pipeline.hdel('carts_%s'%request.user.id,sku_id)
        # 4.3 删除set
        # redis_cli.srem('selected_%s'%request.user.id,sku_id)
        pipeline.srem('selected_%s'%request.user.id,sku_id)
        pipeline.execute()
        # 5. 返回响应
        return JsonResponse({'code':0})


class CartsSelectAllView(View):
    def put(self,request):
        # 1. 接收参数
        data = json.loads(request.body.decode())
        # 2. 提取参数
        selected = data.get('selected',True)
        # 3. 验证参数
        # 4. 数据更新
        # 4.1 链接redis
        redis_cli = get_redis_connection('carts')
        # 4.2 更新hash
        cart = redis_cli.hgetall('carts_%s'%request.user.id)
        sku_id_list = cart.keys()
        # 4.3 更新set
        if selected:
            redis_cli.sadd('selected_%s' % request.user.id, *sku_id_list)
        else:
            redis_cli.srem('selected_%s' % request.user.id, *sku_id_list)
        # 5. 返回响应
        return JsonResponse({'code': 0,'errmsg':'全选购物车成功'})



class CartsSimpleView(LoginRequiredMixin,View):
    def get(self,request):
        # 查看redis购物车数据
        redis_conn = get_redis_connection('carts')
        redis_cart = redis_conn.hgetall('carts_%s' % request.user.id)
        cart_selected = redis_conn.smembers('selected_%s' % request.user.id)
        # 将redis中两个数据统一格式
        cart_dict = {}
        for sku_id, count in redis_cart.items():
            cart_dict[int(sku_id)] = {
                'count': int(count),
                'selected': sku_id in cart_selected
            }
        # 构造简单购物车JSON数据
        cart_skus = []
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_skus.append({
                "id":sku.id,
                "name":sku.name,
                "count":cart_dict.get(sku.id).get('count'),
                "default_image_url":sku.default_image.url
            })

        # 返回响应
        return http.JsonResponse({"code":0,"errmsg":"ok","cart_skus":cart_skus})




































































